package com.lure.base.statemachine;

import com.lure.base.statemachine.exception.StateMachineException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 状态机工厂类
 * @author yanwei li create  2024-05-28 18:14
 */
public class StateMachineFactory {

    static Map<String /* machineId*/, StateMachine> stateMachineMap = new ConcurrentHashMap<>();

    public static<S,E,C> void register(StateMachine<S,E,C> stateMachine){
        final String machineId = stateMachine.getMachineId();
        if (stateMachineMap.get(machineId) != null){
            throw new StateMachineException("StateMachineImpl has been created ,machineId is "+stateMachine.getMachineId()+" .");
        }
        stateMachineMap.put(stateMachine.getMachineId(),stateMachine);
    }

    public static<S,E,C> StateMachine get(String machineId){
        StateMachine stateMachine = stateMachineMap.get(machineId);
        if(stateMachine == null){
            throw new StateMachineException("There is no stateMachine instance for "+machineId+", please build it first");
        }
        return stateMachine;
    }

}
